Python | a += b is not always a = a + b

In Python, a+=b is not always a=a+b. We will see this aspect with the help of som examples.

Example: In this example, we can see that list2 which is pointing to list1 gets changes without creating a new object. We can see that the content of list1 and list2 are same. It is because we are using a+=b.

Python3




list1 = [5, 4, 3, 2, 1]
list2 = list1
list1 += [1, 2, 3, 4] # modifying value in current reference
 
# as on line 4 it modify the value without creating new object
# variable list2 which is pointing to list1 gets changes
print(list1)
print(list2)


Output

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1, 1, 2, 3, 4]

Example: In this example, we can see that the contents of list1 are same as above but the content of list 2 are different. It is because we are using a=a+b in this example.

Python3




list1 = [5, 4, 3, 2, 1]
list2 = list1
list1 = list1 + [1, 2, 3, 4]
 
# Contents of list1 are same as above
# program, but contents of list2 are
# different.
print(list1)
print(list2)


Output

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1]



Python | a += b is not always a = a + b

In Python, a += b doesn’t always behave the same way as a = a + b, the same operands may give different results under different conditions. But to understand why they show different behaviors you have to deep dive into the working of variables. before that, we will try to understand the difference between Python Variable and List Reference in Python.

Similar Reads

Difference Between Variable and List Reference

Here, we will see the difference between variable and list reference....

Python | a += b is not always a = a + b

...